package control;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Dao.UserDao;
import Dao.UserDaoimpl;
import entity.User;


public class Login extends HttpServlet{
	UserDao userdao = new UserDaoimpl(); 
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		System.out.println("login post");
		req.setCharacterEncoding("utf-8");
		String email = req.getParameter("email");
		String password = req.getParameter("password");
		User user = null;
		try {
			user = userdao.getUser(email,password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		resp.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("Gbk");
		if(user==null){
			resp.getWriter().print("<script charset=\"utf-8\"> alert(\"账号名或密码错误\"); window.history.back(-1);</script>");
			return ;
		}else {
			Cookie cookie = new Cookie("email",email);
			cookie.setMaxAge(36000);
			Cookie cookie2 = new Cookie("typeid",user.getTypeid().toString());
			cookie2.setMaxAge(36000);
			Cookie cookie3 = new Cookie("password",password);
			cookie3.setMaxAge(36000);
			resp.addCookie(cookie);
			resp.addCookie(cookie2);
			resp.addCookie(cookie3);
			System.out.println("/success.html");
			if(user.getTypeid()==0) {
				resp.sendRedirect(req.getContextPath()+"/user/index.html");//跳转
			}else {
				resp.sendRedirect(req.getContextPath()+"/admin/index.html");//跳转
			}
			
			return ;
		}
	}	
}
